package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Lenovo
* @description 针对表【tb_dict(字典表)】的数据库操作Service实现
* @createDate 2025-06-24 10:34:29
*/
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{

    @Autowired
    TbDictMapper tbDictMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void loadDictList(){
        System.out.println("项目启动时，加载字典列表到缓存中");

        List<TbDict> tbDictList = tbDictMapper.selectList(null);

        for (TbDict tbDict : tbDictList) {
            String key1 = "dict-" + tbDict.getDictType();
            String key2 = tbDict.getDictValue()+"";

            stringRedisTemplate.opsForHash().put(key1,key2, JSON.toJSONString(tbDict));
        }

        System.out.println("加载字典数据完成");

    }

    @Override
    public R getDictList(Integer typeId) {
        String key = "dict-"+typeId;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if(hasKey){
            System.out.println("从缓存中读取字典列表");
            List<Object> values = stringRedisTemplate.opsForHash().values(key);
            List<TbDict> tbDictList = values.stream().map(item -> {
                TbDict tbDict = JSON.parseObject(item.toString(), TbDict.class);
                return tbDict;
            }).collect(Collectors.toList());

            return R.ok(tbDictList);
        }

        System.out.println("从数据库中读取字典列表");
        List<TbDict> tbDicts = tbDictMapper.selectList(
                new LambdaQueryWrapper<TbDict>().eq(TbDict::getDictType, typeId)
        );
        return R.ok(tbDicts);
    }
}




